<template>
  <div>
    <el-dialog
      v-model="dialogFormVisible"
      :title="titleInfo"
      @close="handleCancel"
    >
      <el-form
        ref="listQueryRef"
        :rules="listQueryRules"
        :model="listQuery"
        label-width="100"
      >
        <el-form-item label="头像" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :limit="1"
            :action="''"
            accept=".png,.jpg,.jpeg"
            :on-progress="handlePictureCardPreview"
            :data="additionalData"
            :http-request="UploadFileFn"
            :before-upload="handleBeforeUpload"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
              prop="imageUrl"
            />
          </el-upload>
        </el-form-item>
        <el-form-item label="名字" prop="name">
          <el-input
            class="!w-[300px]"
            v-model="listQuery.name"
            placeholder="请输入名字"
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            class="!w-[300px]"
            v-model.number="listQuery.phone"
            autocomplete="off"
            maxlength="11"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="card">
          <el-input
            class="!w-[300px]"
            v-model="listQuery.card"
            autocomplete="off"
            maxlength="18"
            placeholder="请输入身份证号"
            clearable
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="listQuery.status"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input
            class="!w-[300px]"
            placeholder="请输入备注"
            v-model="listQuery.notes"
            autocomplete="off"
            maxlength="50"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialogFormVisible" type="danger"
            >取消</el-button
          >
          <el-button type="primary" :loading="loading" @click="handleSubmit">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getSessionKey } from "@/utils/auth";
import OSS from "ali-oss";
import {
  reactive,
  ref,
  inject,
  onMounted,
  defineProps,
  defineEmits,
  defineExpose
} from "vue";
import { getuFile } from "@/api/user";
import { number } from "echarts";
const chekcPhone = (rule, value, callback) => {
  const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
  if (!value) {
    return callback(new Error("手机号码不能为空"));
  } else if (!reg.test(value)) {
    return callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
};
const listQueryRules = {
  name: [{ required: true, message: "请输入名字", trigger: "blur" }]
  // phone: [
  //   { required: true, message: "请输入手机号", trigger: "blur" },
  //   { validator: chekcPhone, trigger: "change" }
  // ]
  // status: [{ required: true, message: "请选择状态", trigger: "blur" }],
  // notes: [{ required: true, message: "请输入备注", trigger: "blur" }]
};
const imageUrl = ref(
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);
const listQueryRef = ref("");
const baseUrl = ref("http://yuandacaiwuoss.52dashi.com");

const additionalData = reactive({
  // 这里添加你需要传递的额外参数
  type: "admin",
  action: "loan"
});
const props = defineProps({
  isEdit: {
    type: String,
    required: ""
  },
  titleInfo: {
    type: String,
    required: ""
  }
});
const listQuery = reactive({
  admin_id: getSessionKey().admin_id,
  name: "",
  phone: "",
  status: 1,
  notes: "",
  image: "",
  id: ""
});

const dialogFormVisible = ref(false);
const openDialogFormVisible = row => {
  if (props.isEdit == "1") {
    const img = ref(`${baseUrl.value}${row.image}`);
    console.log(row, "");
    listQuery.name = row.name;
    listQuery.phone = row.phone;
    listQuery.admin_id = getSessionKey().admin_id;
    listQuery.status = row.status;
    listQuery.notes = row.notes;
    listQuery.image = row.image;
    listQuery.id = row.id;
    listQuery.card = row.card;
    imageUrl.value = img.value
      ? "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
      : img.value;
  } else {
    imageUrl.value =
      "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png";
  }

  dialogFormVisible.value = true;
};
const closeDialogFormVisible = () => {
  listQueryRef.value.resetFields(); // 清除表单校验以及表单数据初始化
  dialogFormVisible.value = false;
};
const emit = defineEmits(["handleSubmit"]);
const handleSubmit = () => {
  listQueryRef.value.validate(valid => {
    if (valid) {
      // 添加
      const parmas = JSON.parse(JSON.stringify(listQuery));
      emit("handleSubmit", parmas);
    }
  });
};
defineExpose({ openDialogFormVisible, closeDialogFormVisible }); //子组件需要把数据导出去
const handleCancel = () => {
  listQueryRef.value.resetFields(); // 清除表单校验以及表单数据初始化
};
const loading = ref(false);
// 上传图片

const client = new OSS({
  // uploadImageUrl: ` http://yuandacaiwuoss.52dashi.com`, // 默认存在根目录，可根据需求改
  region: "oss-cn-wuhan-lr", // bucket所在的区域， 默认oss-cn-hangzhou
  //secure: true, // secure: 配合region使用，如果指定了secure为true，则使用HTTPS访问
  accessKeyId: "LTAI5tQ54726RmEkCVn9yYeJ", // 通过阿里云控制台创建的AccessKey
  accessKeySecret: "ZgiT3HgIngnwXRylGZuXeZPTOMkATD", // 通过阿里云控制台创建的AccessSecret
  bucket: "yuandacaiwu" // 通过控制台或PutBucket创建的bucket
});
const UploadFileFn = file => {
  const fileName = ref(`/loan/admin/${Date.parse(new Date())}`);
  console.log(file, "sahngchuan");
  client.put(fileName.value, file.file).then(res => {
    console.log(res); 
    listQuery.image = fileName.value;
    imageUrl.value = res.url;
    console.log(listQuery.image);
  });
};

const handleBeforeUpload = file => {
  const filesInfo = file.size / 1024 / 1024 < 2;
  if (!filesInfo) {
    ElMessageBox.alert("上传头像图片大小不能超过 2MB!");
  }
  return;
  // new Promise((resolve, reject) => {
  //   const reader = new FileReader();
  //   reader.onload = e => {
  //     // 转换成功，得到Base64字符串
  //     const base64 = e.target.result;
  //     // 处理Base64字符串，例如可以在这里发起接口请求
  //     const params = {
  //       ...additionalData,
  //       file: base64
  //     };
  //     getuFile(params).then(res => {
  //       if (res.code == 200) {
  //         imageUrl.value = base64;
  //         listQuery.value.image = res.data;
  //       }
  //     });
  //   };
  //   reader.onerror = reject;
  //   reader.readAsDataURL(file); // 转换文件为Base64
  // });
};
</script>

<style lang="scss" scoped>
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
